<?php

class ReportController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('trialbalance'),
				'roles'=>array('member'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('trialbalance','incomestatment','balancesheet'),
				'roles'=>array('admin', 'accountant'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * generate  a trial balance.
	 * @param date $date the date of trial balance to be displayed
	 */
	public function actionTrialBalance()
	{
		$data = Yii::app()->db->createCommand(
			"SELECT glId, codePrefix, codePostfix, title, sum(if(isDebit=1,amount,0)) AS debitAmount, sum(if(isDebit=0,amount,0)) AS creditAmount
			 FROM glTransaction gt 
			 INNER JOIN gl gl ON gl.id=gt.glId
			 GROUP BY glId
			 ORDER BY gl.glType, gl.codePrefix, gl.codePostfix")->queryAll();
		
		$this->render('trialBalance',array(
			'data'=>$data,
		));
	}
	
	/**
	 * generate a T-Account.
	 * @param int $glId id of GL
	 * @param date $date the date 
	 */
	public function actionTeeAccount($glId=0)
	{
		$gl = Gl::model()->findByPk($glId);
		
		$debitData = Yii::app()->db->createCommand(
			"SELECT * 
			FROM gltransaction gt 
			WHERE glId = $glId
			AND isDebit=1
			ORDER BY createDate")->queryAll();
		
		$creditData = Yii::app()->db->createCommand(
			"SELECT * 
			FROM gltransaction gt 
			WHERE glId = $glId
			AND isDebit=0
			ORDER BY createDate")->queryAll();
		
		$this->render('teeAccount',array(
			'glData'=>$gl,
			'debitData'=>$debitData,
			'creditData'=>$creditData,
		));
	}
}
